"use client";

import { useRef, useState, useEffect, useContext, useMemo } from "react";
import {
  Box,
  Flex,
  Grid,
  Heading,
  Text,
  Slider,
  SliderTrack,
  SliderFilledTrack,
  SliderThumb,
  useColorModeValue,
  HStack,
  Input,
} from "@chakra-ui/react";
import KBKeyboardView from "./KBKeyboardView";
import { MainContext } from "@/src/providers/MainProvider";
import { MatrixRenderer } from "../AudioSpectrum/MatrixRenderer";
import AudioLightMapper from "@/src/libs/audioLightMapper";

// 灯光模式类型定义
type LightModeType = {
  id: string;
  lang: string;
  mode: number;
  name: string;
  icon: string;
  isStatic?: boolean;
  supportSpeed?: boolean;
  supportBrightness?: boolean;
  supportSingleColor?: boolean; // 是否支持单色调色板
  category: "dynamic" | "static";
  colorCount?: number;
  brightnessLevels?: number[];
  description: string;
};

function KBLightSetting() {
  const {
    currentLightMode,
    setCurrentLightMode,
    connectedKeyboard,
    lightInfo,
    setLightInfo,
    currentColor,
    setCurrentColor,
    t,
  } = useContext(MainContext);

  const [lightModes, setLightModes] = useState<LightModeType[]>([
    {
      id: "mode_0",
      lang: "300",
      mode: 0x00,
      name: t("1009"),
      icon: "●",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "static",
      description: "波浪",
    },
    {
      id: "mode_1",
      lang: "301",
      mode: 0x01,
      name: t("1010"),
      icon: "◉",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "波光效果",
    },
    {
      id: "mode_2",
      lang: "302",
      mode: 0x02,
      name: t("1011"),
      icon: "✿",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: false,
      category: "dynamic",
      description: "光谱效果",
    },
    {
      id: "mode_3",
      lang: "303",
      mode: 0x03,
      name: t("1012"),
      icon: "❀",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "海浪效果",
    },
    {
      id: "mode_4",
      lang: "325",
      mode: 0x04,
      name: t("1013"),
      icon: "↔",
      supportSpeed: false,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "单点",
    },
    {
      id: "mode_5",
      lang: "326",
      mode: 0x05,
      name: t("1014"),
      icon: "⟲",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "呼吸效果",
    },
    {
      id: "mode_6",
      lang: "327",
      mode: 0x06,
      name: t("1002"),
      icon: "◯",
      supportSpeed: false,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "静态",
    },
    {
      id: "mode_7",
      lang: "328",
      mode: 0x07,
      name: t("1003"),
      icon: "∿",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "扩散",
    },
    {
      id: "mode_8",
      lang: "329",
      mode: 0x08,
      name: t("1004"),
      icon: "⊕",
      supportSpeed: false,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "梅花效果",
    },
    {
      id: "mode_9",
      lang: "320",
      mode: 0x09,
      name: t("1005"),
      icon: "〜",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: false,
      category: "dynamic",
      description: "百花效果",
    },
    {
      id: "mode_10",
      lang: "321",
      mode: 0x0a,
      name: t("1006"),
      icon: "◐",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "一字放射效果",
    },
    {
      id: "mode_11",
      lang: "322",
      mode: 0x0b,
      name: t("1001"),
      icon: "⊛",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "蛇形跑马灯效果",
    },
    {
      id: "mode_12",
      lang: "323",
      mode: 0x0c,
      name: t("1008"),
      icon: "≈",
      supportSpeed: true,
      supportBrightness: true,
      supportSingleColor: false,
      category: "dynamic",
      description: "汇聚效果",
    },
    {
      id: "mode_13",
      lang: "324",
      mode: 0x0d,
      name: t("1029"),
      icon: "●",
      supportSpeed: false,
      supportBrightness: true,
      supportSingleColor: true,
      category: "dynamic",
      description: "自定义灯效",
    },
    {
      id: "mode_14",
      lang: "0",
      mode: 0x0e, // 14
      name: t("1030"),
      icon: "●",
      supportSpeed: false,
      supportBrightness: false,
      supportSingleColor: false,
      category: "dynamic",
      description: "音乐律动效果",
    },
  ]);

  const containerRef = useRef<HTMLDivElement>(null);
  const [keyboardHeight, setKeyboardHeight] = useState("40vh");

  // 状态管理
  const [lightType, setLightType] = useState("backlight"); // 'backlight' 或 'keylight'
  const [selectedMode, setSelectedMode] = useState(currentLightMode); // 默认选中"静态"
  const [speed, setSpeed] = useState(3); // 速度范围0~3，默认中间值
  const [brightness, setBrightness] = useState(200); // 亮度范围0~255，默认中间值
  const [direction, setDirection] = useState("向右");
  const [isCustomColor, setIsCustomColor] = useState(false);
  const [colorPickerPosition, setColorPickerPosition] = useState({
    x: 20,
    y: 30,
  }); // 调色板选择点位置
  const [hueSliderPosition, setHueSliderPosition] = useState(50); // 色相条位置
  const [rgbValues, setRgbValues] = useState({ r: 0, g: 145, b: 255 }); // RGB值
  const [isDragging, setIsDragging] = useState(false); // 是否正在拖拽
  const [dragType, setDragType] = useState<"palette" | "hue" | null>(null); // 拖拽类型
  const [selectedPreset, setSelectedPreset] = useState<number | null>(null); // 选中的预设颜色

  const lightEffectRef = useRef<HTMLDivElement>(null);
  const [lightEffectWidth, setLightEffectWidth] = useState<number>(0);
  const [lightEffectHeight, setLightEffectHeight] = useState<number>(0);

  useEffect(() => {
    if (lightEffectRef.current) {
      const resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          setLightEffectWidth(entry.contentRect.width * 1.18);
          setLightEffectHeight(entry.contentRect.height * 0.88);
        }
      });

      resizeObserver.observe(lightEffectRef.current);

      return () => resizeObserver.disconnect();
    }
  }, []);

  // 样式计算
  const bgColor = useColorModeValue(
    "rgba(255, 255, 255, 0.5)",
    "rgba(30, 30, 35, 0.5)"
  );
  const cardBgColor = useColorModeValue(
    "rgba(255, 255, 255, 0.5)",
    "rgba(255, 255, 255, 0.5)"
  );
  const selectedCardBgColor = useColorModeValue(
    "rgb(255, 140, 0)",
    "rgb(255, 140, 0)"
  );
  const textColor = "black"; // 所有文字颜色设为黑色
  const cardTextColor = "black"; // 卡片内文字颜色设为黑色
  const sliderThumbColor = "rgb(255, 140, 0)";
  const sliderTrackColor = useColorModeValue(
    "rgba(255, 255, 255, 0.2)",
    "rgba(255, 255, 255, 0.2)"
  );
  const sliderFilledTrackColor = useColorModeValue(
    "rgb(255, 140, 0)",
    "rgb(255, 140, 0)"
  );

  const isElectron = useMemo(() => {
    if (typeof navigator !== "undefined") {
      return navigator.userAgent.toLowerCase().indexOf("electron") !== -1;
    } else {
      console.log("运行在服务器端，没有 navigator");
    }
  }, []);

  // 根据窗口大小调整高度
  useEffect(() => {
    if (!isElectron) {
      setLightModes((prevModes) =>
        prevModes.filter((mode) => mode.id !== "mode_14")
      );
    }

    setUiColLevels([]);

    const updateHeight = () => {
      setKeyboardHeight("40vh");
    };

    updateHeight();
    window.addEventListener("resize", updateHeight);

    return () => {
      window.removeEventListener("resize", updateHeight);
    };
  }, [isElectron]);

  // 音频频谱矩阵显示状态
  const [showAudioMatrix, setShowAudioMatrix] = useState(false);

  // 音频灯光映射器
  const audioLightMapper = useMemo(() => new AudioLightMapper(), []);

  // 页面键盘预览的亮度系数（0-1），用于和音频联动
  const [uiLightFactor, setUiLightFactor] = useState(0);
  // 页面键盘预览的每列层级（0..rows），与 matrixGrid 同步
  const [uiColLevels, setUiColLevels] = useState<number[]>([]);

  // 处理灯光模式选择
  const handleLightMode = (modeIndex: number, mode: LightModeType) => {
    console.log("handleLightMode", modeIndex, mode);
    if (mode.id === "mode_14") {
      if (connectedKeyboard) {
        // 发送进入音乐律动模式命令
        connectedKeyboard.startMusicalGroove();
      }
      setShowAudioMatrix(true);
      // setCurrentLightMode(-1);

      return;
    } else {
      if (connectedKeyboard) {
        // 发送退出音乐律动模式命令
        connectedKeyboard.stopMusicalGroove();
      }
    }

    setUiColLevels([]);
    setShowAudioMatrix(false);
    setSelectedMode(modeIndex);
    setCurrentLightMode(modeIndex);

    if (connectedKeyboard) {
      try {
        // 创建新的灯光信息对象
        const newLightInfo: any = {
          name: `Light${modeIndex}`,
          lang: "",
          status: 1, // 开启状态
          type: lightType === "backlight" ? 0 : 1, // 0=背光, 1=键光
          mode: modeIndex, // 灯光模式 0-21
          brightness: brightness, // 亮度 0-4
          speed: speed, // 速度 0-255
          direction: direction === "向右" ? 0 : 1, // 方向 0=向右, 1=向左
          colorful: selectedPreset === 7 ? 1 : 0, // 混彩标志
          colorValue: parseInt(currentColor.replace("#", ""), 16), // 颜色值
          colorIndex: selectedPreset || 0, // 预设颜色索引
          lockWin: 0,
          lockAltF4: 0,
          lockAltTab: 0,
        };

        // 更新lightInfo数组
        const updatedLightInfo = [...lightInfo];
        if (updatedLightInfo[modeIndex]) {
          updatedLightInfo[modeIndex] = {
            ...updatedLightInfo[modeIndex],
            ...newLightInfo,
          };
        } else {
          updatedLightInfo[modeIndex] = newLightInfo;
        }
        setLightInfo(updatedLightInfo);

        // 发送到设备
        connectedKeyboard.setLightInfo(newLightInfo);
      } catch (error) {
        console.error("设置灯光模式失败:", error);
      }
    }
  };

  // 处理亮度调节
  const handleBrightness = (value: number) => {
    setBrightness(value);

    if (connectedKeyboard) {
      try {
        // 创建更新的灯光信息
        const updatedLightInfo = lightInfo.map((item: any, index: number) =>
          index === selectedMode
            ? {
                ...item,
                brightness: value,
              }
            : item
        );

        setLightInfo(updatedLightInfo);

        // 发送到设备
        if (updatedLightInfo[selectedMode]) {
          connectedKeyboard.setLightInfo(updatedLightInfo[selectedMode]);
        }

        console.log("设置亮度:", value);
      } catch (error) {
        console.error("设置亮度失败:", error);
      }
    }
  };

  // 处理速度调节
  const handleSpeed = (value: number) => {
    setSpeed(value);

    if (connectedKeyboard) {
      try {
        // 创建更新的灯光信息
        const updatedLightInfo = lightInfo.map((item: any, index: number) =>
          index === selectedMode
            ? {
                ...item,
                speed: value,
              }
            : item
        );

        setLightInfo(updatedLightInfo);

        // 发送到设备
        if (updatedLightInfo[selectedMode]) {
          connectedKeyboard.setLightInfo(updatedLightInfo[selectedMode]);
        }

        console.log("设置速度:", value);
      } catch (error) {
        console.error("设置速度失败:", error);
      }
    }
  };

  // 处理方向变化
  const handleDirectionChange = (newDirection: string) => {
    setDirection(newDirection);

    if (connectedKeyboard) {
      try {
        // 创建更新的灯光信息
        const updatedLightInfo = lightInfo.map((item: any, index: number) =>
          index === selectedMode
            ? {
                ...item,
                direction: newDirection === "向右" ? 0 : 1,
              }
            : item
        );

        setLightInfo(updatedLightInfo);

        // 发送到设备
        if (updatedLightInfo[selectedMode]) {
          connectedKeyboard.setLightInfo(updatedLightInfo[selectedMode]);
        }

        console.log("设置方向:", newDirection);
      } catch (error) {
        console.error("设置方向失败:", error);
      }
    }
  };

  // 处理颜色变化
  const handleColorChange = (newColor: string, presetIndex?: number) => {
    setCurrentColor(newColor);
    if (presetIndex !== undefined) {
      setSelectedPreset(presetIndex);
    } else {
      setSelectedPreset(null); // 清除预设选择
    }
    if (connectedKeyboard) {
      try {
        // 创建更新的灯光信息
        const updatedLightInfo = lightInfo.map((item: any, index: number) =>
          index === selectedMode
            ? {
                ...item,
                colorValue: parseInt(newColor.replace("#", ""), 16),
                colorful: presetIndex === 7 ? 1 : 0,
              }
            : item
        );
        console.log(
          "newColor",
          newColor,
          parseInt(newColor.replace("#", ""), 16)
        );
        setLightInfo(updatedLightInfo);

        // 发送到设备
        if (updatedLightInfo[selectedMode]) {
          connectedKeyboard.setLightInfo(updatedLightInfo[selectedMode]);
        }

        console.log("设置颜色:", newColor, "预设索引:", presetIndex);
      } catch (error) {
        console.error("设置颜色失败:", error);
      }
    }
  };

  // RGB转HEX
  const rgbToHex = (r: number, g: number, b: number) => {
    return (
      "#" +
      ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase()
    );
  };

  // HEX转RGB
  const hexToRgb = (hex: string) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16),
        }
      : null;
  };

  // HSV转RGB
  const hsvToRgb = (h: number, s: number, v: number) => {
    const c = v * s;
    const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
    const m = v - c;
    let r = 0,
      g = 0,
      b = 0;

    if (0 <= h && h < 60) {
      r = c;
      g = x;
      b = 0;
    } else if (60 <= h && h < 120) {
      r = x;
      g = c;
      b = 0;
    } else if (120 <= h && h < 180) {
      r = 0;
      g = c;
      b = x;
    } else if (180 <= h && h < 240) {
      r = 0;
      g = x;
      b = c;
    } else if (240 <= h && h < 300) {
      r = x;
      g = 0;
      b = c;
    } else if (300 <= h && h < 360) {
      r = c;
      g = 0;
      b = x;
    }

    return {
      r: Math.round((r + m) * 255),
      g: Math.round((g + m) * 255),
      b: Math.round((b + m) * 255),
    };
  };

  // 处理调色板交互
  const handleColorPaletteInteraction = (
    event: React.MouseEvent<HTMLDivElement>
  ) => {
    const rect = event.currentTarget.getBoundingClientRect();
    const x = Math.max(
      0,
      Math.min(100, ((event.clientX - rect.left) / rect.width) * 100)
    );
    const y = Math.max(
      0,
      Math.min(100, ((event.clientY - rect.top) / rect.height) * 100)
    );

    setColorPickerPosition({ x, y });

    // 根据位置计算颜色
    const hue = (hueSliderPosition / 100) * 360;
    const saturation = x / 100;
    const value = 1 - y / 100;

    const rgb = hsvToRgb(hue, saturation, value);
    setRgbValues(rgb);
    const newColor = rgbToHex(rgb.r, rgb.g, rgb.b);
    handleColorChange(newColor); // 使用新的颜色处理函数
  };

  // 处理调色板鼠标按下
  const handleColorPaletteMouseDown = (
    event: React.MouseEvent<HTMLDivElement>
  ) => {
    setIsDragging(true);
    setDragType("palette");
    handleColorPaletteInteraction(event);
  };

  // 处理色相条交互
  const handleHueSliderInteraction = (
    event: React.MouseEvent<HTMLDivElement>
  ) => {
    const rect = event.currentTarget.getBoundingClientRect();
    const x = Math.max(
      0,
      Math.min(100, ((event.clientX - rect.left) / rect.width) * 100)
    );

    setHueSliderPosition(x);

    // 根据当前调色板位置和新色相计算颜色
    const hue = (x / 100) * 360;
    const saturation = colorPickerPosition.x / 100;
    const value = 1 - colorPickerPosition.y / 100;

    const rgb = hsvToRgb(hue, saturation, value);
    setRgbValues(rgb);
    const newColor = rgbToHex(rgb.r, rgb.g, rgb.b);
    handleColorChange(newColor); // 使用新的颜色处理函数
  };

  // 处理色相条鼠标按下
  const handleHueSliderMouseDown = (
    event: React.MouseEvent<HTMLDivElement>
  ) => {
    setIsDragging(true);
    setDragType("hue");
    handleHueSliderInteraction(event);
  };

  // 处理鼠标移动
  const handleMouseMove = (event: React.MouseEvent<HTMLDivElement>) => {
    if (!isDragging) return;

    if (dragType === "palette") {
      handleColorPaletteInteraction(event);
    } else if (dragType === "hue") {
      handleHueSliderInteraction(event);
    }
  };

  // 处理鼠标松开
  const handleMouseUp = () => {
    setIsDragging(false);
    setDragType(null);
  };

  // 添加全局鼠标事件监听
  useEffect(() => {
    if (isDragging) {
      const handleGlobalMouseMove = (event: MouseEvent) => {
        if (dragType === "palette") {
          const paletteElement = document.querySelector(
            "[data-color-palette]"
          ) as HTMLElement;
          if (paletteElement) {
            const rect = paletteElement.getBoundingClientRect();
            const x = Math.max(
              0,
              Math.min(100, ((event.clientX - rect.left) / rect.width) * 100)
            );
            const y = Math.max(
              0,
              Math.min(100, ((event.clientY - rect.top) / rect.height) * 100)
            );

            setColorPickerPosition({ x, y });

            const hue = (hueSliderPosition / 100) * 360;
            const saturation = x / 100;
            const value = 1 - y / 100;

            const rgb = hsvToRgb(hue, saturation, value);
            setRgbValues(rgb);
            const newColor = rgbToHex(rgb.r, rgb.g, rgb.b);
            handleColorChange(newColor); // 使用新的颜色处理函数
          }
        } else if (dragType === "hue") {
          const hueElement = document.querySelector(
            "[data-hue-slider]"
          ) as HTMLElement;
          if (hueElement) {
            const rect = hueElement.getBoundingClientRect();
            const x = Math.max(
              0,
              Math.min(100, ((event.clientX - rect.left) / rect.width) * 100)
            );

            setHueSliderPosition(x);

            const hue = (x / 100) * 360;
            const saturation = colorPickerPosition.x / 100;
            const value = 1 - colorPickerPosition.y / 100;

            const rgb = hsvToRgb(hue, saturation, value);
            setRgbValues(rgb);
            const newColor = rgbToHex(rgb.r, rgb.g, rgb.b);
            handleColorChange(newColor); // 使用新的颜色处理函数
          }
        }
      };

      const handleGlobalMouseUp = () => {
        setIsDragging(false);
        setDragType(null);
      };

      document.addEventListener("mousemove", handleGlobalMouseMove);
      document.addEventListener("mouseup", handleGlobalMouseUp);

      return () => {
        document.removeEventListener("mousemove", handleGlobalMouseMove);
        document.removeEventListener("mouseup", handleGlobalMouseUp);
      };
    }
  }, [
    isDragging,
    dragType,
    hueSliderPosition,
    colorPickerPosition.x,
    colorPickerPosition.y,
  ]);

  // 处理RGB输入变化
  const handleRgbChange = (component: "r" | "g" | "b", value: string) => {
    const numValue = Math.max(0, Math.min(255, parseInt(value) || 0));
    const newRgb = { ...rgbValues, [component]: numValue };
    setRgbValues(newRgb);
    const newColor = rgbToHex(newRgb.r, newRgb.g, newRgb.b);
    handleColorChange(newColor); // 使用新的颜色处理函数
  };

  // 处理HEX输入变化
  const handleHexChange = (value: string) => {
    if (value.match(/^#[0-9A-Fa-f]{6}$/)) {
      const rgb = hexToRgb(value);
      if (rgb) {
        setRgbValues(rgb);
      }
      handleColorChange(value); // 使用新的颜色处理函数
    }
  };

  // 预设颜色数组
  const presetColors = [
    { name: "红色", color: "#FF0000" },
    { name: "绿色", color: "#00FF00" },
    { name: "蓝色", color: "#0000FF" },
    { name: "黄色", color: "#FFFF00" },
    { name: "紫色", color: "#FF00FF" },
    { name: "青色", color: "#00FFFF" },
    { name: "白色", color: "#FFFFFF" },
  ];

  // 处理预设颜色选择
  const handlePresetColorSelect = (index: number, color: string) => {
    handleColorChange(color, index);
    setIsCustomColor(false);
  };

  // 处理混彩选择
  const handleMixedColorSelect = () => {
    handleColorChange(currentColor, 7); // 混彩的索引为7
    setIsCustomColor(true);
  };

  const handleCloseAudioMatrix = () => {
    setShowAudioMatrix(false);
    setUiColLevels([]);
  };

  return (
    <Box
      ref={containerRef}
      className="w-full h-full flex flex-col"
      style={{
        marginLeft: "25px",
        width: "calc(100% - 50px)",
      }}
    >
      {/* 键盘预览区域 */}
      <Box
        style={{
          height: keyboardHeight,
          padding: "10px",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <KBKeyboardView
          uiLightFactor={uiLightFactor}
          uiColLevels={uiColLevels}
        />
      </Box>

      {/* 灯光控制区域 */}
      <Box
        className="relative"
        p={6}
        style={{
          flex: 1,
          backgroundColor: bgColor,
          borderRadius: "8px",
          margin: "0 10px 10px 10px",
          overflow: "hidden",
          background: "rgba(255, 255, 255, 0.5)",
          backdropFilter: "blur(20px)",
          WebkitBackdropFilter: "blur(20px)",
          border: "1px solid rgba(255, 140, 0, 0.2)",
          boxShadow: "0 8px 32px rgba(255, 140, 0, 0.1)",
        }}
      >
        {/* 主要内容区域 - 三列布局 */}
        <Grid templateColumns="1fr 1fr 1fr" gap={8} height="calc(100% - 40px)">
          {/* 左侧 - 灯光效果 */}
          <Box ref={lightEffectRef}>
            <Heading size="sm" mb={4} color={textColor}>
              {t("1015")}
            </Heading>
            <Grid
              templateColumns="repeat(3, 1fr)"
              gap={2}
              h="100%"
              maxH="280px"
              overflowY="auto"
              pr={3}
              css={{
                "&::-webkit-scrollbar": {
                  width: "10px",
                },
                "&::-webkit-scrollbar-track": {
                  background: "rgba(255, 140, 0, 0.15)",
                  borderRadius: "12px",
                  border: "2px solid rgba(255, 140, 0, 0.3)",
                  margin: "4px 0",
                },
                "&::-webkit-scrollbar-thumb": {
                  background:
                    "linear-gradient(180deg, rgba(255, 140, 0, 0.8), rgba(255, 140, 0, 0.9))",
                  borderRadius: "12px",
                  border: "2px solid rgba(255, 140, 0, 1)",
                  boxShadow: "0 2px 8px rgba(255, 140, 0, 0.3)",
                },
                "&::-webkit-scrollbar-thumb:hover": {
                  background:
                    "linear-gradient(180deg, rgba(255, 140, 0, 0.9), rgba(255, 140, 0, 1))",
                  boxShadow: "0 4px 12px rgba(255, 140, 0, 0.5)",
                },
                "&::-webkit-scrollbar-thumb:active": {
                  background: "rgba(255, 140, 0, 1)",
                },
                "&::-webkit-scrollbar-corner": {
                  background: "transparent",
                },
              }}
            >
              {lightModes.map((mode, index) => (
                <Box
                  key={mode.id}
                  p={3}
                  textAlign="center"
                  borderRadius="md"
                  cursor="pointer"
                  bg={
                    selectedMode === index ? selectedCardBgColor : cardBgColor
                  }
                  onClick={() => handleLightMode(index, mode)}
                  transition="all 0.2s ease"
                  border="1px solid"
                  borderColor={
                    selectedMode === index
                      ? "rgb(255, 140, 0)"
                      : "rgba(255, 140, 0, 0.2)"
                  }
                  _hover={{
                    bg:
                      selectedMode === index
                        ? selectedCardBgColor
                        : "rgba(255, 140, 0, 0.1)",
                    borderColor: "rgba(255, 140, 0, 0.5)",
                    transform: "translateY(-1px)",
                  }}
                  boxShadow={
                    selectedMode === index
                      ? "0 4px 12px rgba(255, 140, 0, 0.3)"
                      : "0 2px 4px rgba(255, 140, 0, 0.1)"
                  }
                  style={{
                    backdropFilter: "blur(8px)",
                    WebkitBackdropFilter: "blur(8px)",
                  }}
                >
                  <Text fontSize="lg" mb={1} color={cardTextColor}>
                    {mode.icon}
                  </Text>
                  <Text
                    fontSize="xs"
                    fontWeight={selectedMode === index ? "bold" : "normal"}
                    color="black"
                    noOfLines={1}
                  >
                    {mode.name}
                  </Text>
                </Box>
              ))}
            </Grid>
          </Box>

          {/* 中间 - 灯光参数 */}
          {!showAudioMatrix && (
            <Box>
              <Heading size="sm" mb={4} color={textColor}>
                {t("1016")}
              </Heading>

              {/* 灯光方向 */}
              {false && (
                <Box mb={6}>
                  <Text
                    fontSize="sm"
                    color={textColor}
                    mb={2}
                    fontWeight="medium"
                  >
                    灯光方向
                  </Text>
                  <HStack spacing={6}>
                    <Box
                      as="button"
                      onClick={() => handleDirectionChange("向左")}
                      bg={
                        direction === "向左"
                          ? "rgb(255, 140, 0)"
                          : "rgba(255, 255, 255, 0.5)"
                      }
                      border="1px solid"
                      borderColor={
                        direction === "向左"
                          ? "rgb(255, 140, 0)"
                          : "rgba(255, 140, 0, 0.3)"
                      }
                      borderRadius="md"
                      px={6}
                      py={3}
                      minW="80px"
                      display="flex"
                      alignItems="center"
                      justifyContent="center"
                      cursor="pointer"
                      transition="all 0.2s ease"
                      _hover={{
                        bg:
                          direction === "向左"
                            ? "rgb(255, 140, 0)"
                            : "rgba(255, 140, 0, 0.1)",
                        borderColor: "rgba(255, 140, 0, 0.5)",
                        transform: "translateY(-1px)",
                      }}
                      boxShadow={
                        direction === "向左"
                          ? "0 4px 12px rgba(255, 140, 0, 0.3)"
                          : "0 2px 4px rgba(255, 140, 0, 0.1)"
                      }
                      style={{
                        backdropFilter: "blur(8px)",
                        WebkitBackdropFilter: "blur(8px)",
                      }}
                    >
                      <Text fontSize="xl" color="black" fontWeight="bold">
                        ←
                      </Text>
                    </Box>
                    <Box
                      as="button"
                      onClick={() => handleDirectionChange("向右")}
                      bg={
                        direction === "向右"
                          ? "rgb(255, 140, 0)"
                          : "rgba(255, 255, 255, 0.5)"
                      }
                      border="1px solid"
                      borderColor={
                        direction === "向右"
                          ? "rgb(255, 140, 0)"
                          : "rgba(255, 140, 0, 0.3)"
                      }
                      borderRadius="md"
                      px={6}
                      py={3}
                      minW="80px"
                      display="flex"
                      alignItems="center"
                      justifyContent="center"
                      cursor="pointer"
                      transition="all 0.2s ease"
                      _hover={{
                        bg:
                          direction === "向右"
                            ? "rgb(255, 140, 0)"
                            : "rgba(255, 140, 0, 0.1)",
                        borderColor: "rgba(255, 140, 0, 0.5)",
                        transform: "translateY(-1px)",
                      }}
                      boxShadow={
                        direction === "向右"
                          ? "0 4px 12px rgba(255, 140, 0, 0.3)"
                          : "0 2px 4px rgba(255, 140, 0, 0.1)"
                      }
                      style={{
                        backdropFilter: "blur(8px)",
                        WebkitBackdropFilter: "blur(8px)",
                      }}
                    >
                      <Text fontSize="xl" color="black" fontWeight="bold">
                        →
                      </Text>
                    </Box>
                  </HStack>
                </Box>
              )}

              {/* 灯光亮度 */}
              <Box mb={6}>
                <Flex justify="space-between" align="center" mb={3}>
                  <Text color={textColor} fontWeight="medium" fontSize="sm">
                    {t("1018")}
                  </Text>
                  <Box
                    bg="rgba(255, 140, 0, 0.75)"
                    px={3}
                    py={1}
                    borderRadius="full"
                    display="flex"
                    alignItems="center"
                    justifyContent="center"
                    minWidth="36px"
                    backdropFilter="blur(4px)"
                    boxShadow="0 2px 6px rgba(255, 140, 0, 0.2)"
                  >
                    <Text fontWeight="bold" color="black" fontSize="sm">
                      {brightness}
                    </Text>
                  </Box>
                </Flex>
                <Slider
                  value={brightness}
                  onChange={handleBrightness}
                  min={0}
                  max={255}
                  step={1}
                >
                  <SliderTrack
                    bg={sliderTrackColor}
                    h="6px"
                    borderRadius="full"
                  >
                    <SliderFilledTrack
                      bg={sliderFilledTrackColor}
                      borderRadius="full"
                    />
                  </SliderTrack>
                  <SliderThumb
                    boxSize={5}
                    bg="white"
                    border="2px solid"
                    borderColor={sliderThumbColor}
                    _focus={{ boxShadow: `0 0 0 3px rgba(255, 140, 0, 0.3)` }}
                  />
                </Slider>
              </Box>

              {/* 灯光速度 - 只在支持速度的模式下显示 */}
              {lightModes[selectedMode]?.supportSpeed && (
                <Box>
                  <Flex justify="space-between" align="center" mb={3}>
                    <Text color={textColor} fontWeight="medium" fontSize="sm">
                      {t("1027")}
                    </Text>
                    <Box
                      bg="rgba(255, 140, 0, 0.75)"
                      px={3}
                      py={1}
                      borderRadius="full"
                      display="flex"
                      alignItems="center"
                      justifyContent="center"
                      minWidth="36px"
                      backdropFilter="blur(4px)"
                      boxShadow="0 2px 6px rgba(255, 140, 0, 0.2)"
                    >
                      <Text fontWeight="bold" color="black" fontSize="sm">
                        {speed}
                      </Text>
                    </Box>
                  </Flex>
                  <Slider
                    value={speed}
                    onChange={handleSpeed}
                    min={0}
                    max={4}
                    step={1}
                  >
                    <SliderTrack
                      bg={sliderTrackColor}
                      h="6px"
                      borderRadius="full"
                    >
                      <SliderFilledTrack
                        bg={sliderFilledTrackColor}
                        borderRadius="full"
                      />
                    </SliderTrack>
                    <SliderThumb
                      boxSize={5}
                      bg="white"
                      border="2px solid"
                      borderColor={sliderThumbColor}
                      _focus={{ boxShadow: `0 0 0 3px rgba(255, 140, 0, 0.3)` }}
                    />
                  </Slider>
                </Box>
              )}
            </Box>
          )}

          {/* 右侧 - 调色板 */}
          {!showAudioMatrix && (
            <Box>
              <Heading size="sm" mb={4} color={textColor}>
                {t("1017")}
              </Heading>

              {/* 检查当前模式是否支持单色调色板 */}
              {lightModes[selectedMode]?.supportSingleColor ? (
                <>
                  {/* 调色板内容 */}
                  <Box
                    data-color-palette
                    background={`hsl(${
                      (hueSliderPosition / 100) * 360
                    }, 100%, 50%)`}
                    borderRadius="lg"
                    p={4}
                    mb={2}
                    minH="180px"
                    position="relative"
                    cursor={selectedPreset === 7 ? "not-allowed" : "crosshair"}
                    border="2px solid rgba(255, 140, 0, 0.3)"
                    opacity={selectedPreset === 7 ? 0.5 : 1}
                    onMouseDown={
                      selectedPreset === 7
                        ? undefined
                        : handleColorPaletteMouseDown
                    }
                    onMouseMove={
                      selectedPreset === 7 ? undefined : handleMouseMove
                    }
                    onMouseUp={selectedPreset === 7 ? undefined : handleMouseUp}
                    _before={{
                      content: '""',
                      position: "absolute",
                      top: 0,
                      left: 0,
                      right: 0,
                      bottom: 0,
                      background:
                        "linear-gradient(to right, white, transparent)",
                      borderRadius: "lg",
                      pointerEvents: "none",
                    }}
                    _after={{
                      content: '""',
                      position: "absolute",
                      top: 0,
                      left: 0,
                      right: 0,
                      bottom: 0,
                      background:
                        "linear-gradient(to bottom, transparent, black)",
                      borderRadius: "lg",
                      pointerEvents: "none",
                    }}
                  >
                    {/* 颜色选择点 */}
                    <Box
                      position="absolute"
                      left={`${colorPickerPosition.x}%`}
                      top={`${colorPickerPosition.y}%`}
                      w="12px"
                      h="12px"
                      borderRadius="full"
                      bg="white"
                      border="2px solid rgba(0, 0, 0, 0.8)"
                      boxShadow="0 2px 8px rgba(0,0,0,0.3)"
                      transform="translate(-50%, -50%)"
                      zIndex={2}
                      pointerEvents="none"
                    />
                  </Box>

                  {/* 色彩条 */}
                  <Box
                    data-hue-slider
                    h="20px"
                    borderRadius="full"
                    background="linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"
                    position="relative"
                    cursor={selectedPreset === 7 ? "not-allowed" : "pointer"}
                    mb={2}
                    opacity={selectedPreset === 7 ? 0.5 : 1}
                    onMouseDown={
                      selectedPreset === 7
                        ? undefined
                        : handleHueSliderMouseDown
                    }
                    onMouseMove={
                      selectedPreset === 7 ? undefined : handleMouseMove
                    }
                    onMouseUp={selectedPreset === 7 ? undefined : handleMouseUp}
                  >
                    {/* 滑块 */}
                    <Box
                      position="absolute"
                      left={`${hueSliderPosition}%`}
                      top="50%"
                      w="16px"
                      h="16px"
                      borderRadius="full"
                      bg="white"
                      border="2px solid rgba(0, 0, 0, 0.8)"
                      boxShadow="0 2px 8px rgba(0,0,0,0.3)"
                      transform="translate(-50%, -50%)"
                      pointerEvents="none"
                    />
                  </Box>

                  {/* 预设颜色选择 - 自定义模式时隐藏 */}
                  {selectedMode !== 13 && (
                    <Box mb={2}>
                      <Text fontSize="xs" color={textColor} mb={2}>
                        {t("1019")}
                      </Text>
                      <Grid templateColumns="repeat(8, 1fr)" gap={1}>
                        {presetColors.map((preset, index) => (
                          <Box
                            key={index}
                            as="button"
                            onClick={() =>
                              handlePresetColorSelect(index, preset.color)
                            }
                            bg={preset.color}
                            borderRadius="md"
                            h="28px"
                            border="2px solid"
                            borderColor={
                              selectedPreset === index
                                ? "rgb(255, 140, 0)"
                                : "rgba(255, 255, 255, 0.3)"
                            }
                            cursor="pointer"
                            transition="all 0.2s ease"
                            _hover={{
                              borderColor: "rgb(255, 140, 0)",
                              transform: "scale(1.05)",
                            }}
                            boxShadow={
                              selectedPreset === index
                                ? "0 0 0 1px rgb(255, 140, 0)"
                                : "0 1px 3px rgba(0,0,0,0.1)"
                            }
                            position="relative"
                          >
                            {selectedPreset === index && (
                              <Box
                                position="absolute"
                                top="50%"
                                left="50%"
                                transform="translate(-50%, -50%)"
                                color="black"
                                fontSize="sm"
                                fontWeight="bold"
                                textShadow="0 0 3px rgba(255,255,255,0.8)"
                              >
                                ✓
                              </Box>
                            )}
                          </Box>
                        ))}
                        {/* 混彩选项 */}
                        <Box
                          as="button"
                          onClick={handleMixedColorSelect}
                          background="linear-gradient(45deg, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"
                          borderRadius="md"
                          h="28px"
                          border="2px solid"
                          borderColor={
                            selectedPreset === 7
                              ? "rgb(255, 140, 0)"
                              : "rgba(255, 255, 255, 0.3)"
                          }
                          cursor="pointer"
                          transition="all 0.2s ease"
                          _hover={{
                            borderColor: "rgb(255, 140, 0)",
                            transform: "scale(1.05)",
                          }}
                          boxShadow={
                            selectedPreset === 7
                              ? "0 0 0 1px rgb(255, 140, 0)"
                              : "0 1px 3px rgba(0,0,0,0.1)"
                          }
                          position="relative"
                        >
                          {selectedPreset === 7 && (
                            <Box
                              position="absolute"
                              top="50%"
                              left="50%"
                              transform="translate(-50%, -50%)"
                              color="black"
                              fontSize="sm"
                              fontWeight="bold"
                              textShadow="0 0 3px rgba(255,255,255,0.8)"
                            >
                              ✓
                            </Box>
                          )}
                        </Box>
                      </Grid>
                    </Box>
                  )}

                  {/* RGB/HEX 输入 */}
                  <Grid templateColumns="repeat(2, 1fr)" gap={2} mb={2}>
                    <Box>
                      <Text fontSize="xs" color={textColor} mb={1}>
                        RGB
                      </Text>
                      <Flex gap={1}>
                        <Input
                          size="sm"
                          value={rgbValues.r}
                          onChange={(e) => handleRgbChange("r", e.target.value)}
                          bg="rgba(255, 255, 255, 0.5)"
                          border="1px solid rgba(255, 140, 0, 0.3)"
                          color={textColor}
                          textAlign="center"
                          borderRadius="md"
                          isDisabled={selectedPreset === 7}
                          opacity={selectedPreset === 7 ? 0.5 : 1}
                          _hover={{
                            bg: "rgba(255, 255, 255, 0.7)",
                            borderColor: "rgba(255, 140, 0, 0.5)",
                          }}
                          _focus={{
                            bg: "rgba(255, 255, 255, 0.8)",
                            borderColor: "rgb(255, 140, 0)",
                            boxShadow: "0 0 0 1px rgb(255, 140, 0)",
                          }}
                        />
                        <Input
                          size="sm"
                          value={rgbValues.g}
                          onChange={(e) => handleRgbChange("g", e.target.value)}
                          bg="rgba(255, 255, 255, 0.5)"
                          border="1px solid rgba(255, 140, 0, 0.3)"
                          color={textColor}
                          textAlign="center"
                          borderRadius="md"
                          isDisabled={selectedPreset === 7}
                          opacity={selectedPreset === 7 ? 0.5 : 1}
                          _hover={{
                            bg: "rgba(255, 255, 255, 0.7)",
                            borderColor: "rgba(255, 140, 0, 0.5)",
                          }}
                          _focus={{
                            bg: "rgba(255, 255, 255, 0.8)",
                            borderColor: "rgb(255, 140, 0)",
                            boxShadow: "0 0 0 1px rgb(255, 140, 0)",
                          }}
                        />
                        <Input
                          size="sm"
                          value={rgbValues.b}
                          onChange={(e) => handleRgbChange("b", e.target.value)}
                          bg="rgba(255, 255, 255, 0.5)"
                          border="1px solid rgba(255, 140, 0, 0.3)"
                          color={textColor}
                          textAlign="center"
                          borderRadius="md"
                          isDisabled={selectedPreset === 7}
                          opacity={selectedPreset === 7 ? 0.5 : 1}
                          _hover={{
                            bg: "rgba(255, 255, 255, 0.7)",
                            borderColor: "rgba(255, 140, 0, 0.5)",
                          }}
                          _focus={{
                            bg: "rgba(255, 255, 255, 0.8)",
                            borderColor: "rgb(255, 140, 0)",
                            boxShadow: "0 0 0 1px rgb(255, 140, 0)",
                          }}
                        />
                      </Flex>
                    </Box>
                    <Box>
                      <Text fontSize="xs" color={textColor} mb={1}>
                        HEX
                      </Text>
                      <Input
                        size="sm"
                        value={currentColor}
                        onChange={(e) => handleHexChange(e.target.value)}
                        bg="rgba(255, 255, 255, 0.5)"
                        border="1px solid rgba(255, 140, 0, 0.3)"
                        color={textColor}
                        textAlign="center"
                        borderRadius="md"
                        isDisabled={selectedPreset === 7}
                        opacity={selectedPreset === 7 ? 0.5 : 1}
                        _hover={{
                          bg: "rgba(255, 255, 255, 0.7)",
                          borderColor: "rgba(255, 140, 0, 0.5)",
                        }}
                        _focus={{
                          bg: "rgba(255, 255, 255, 0.8)",
                          borderColor: "rgb(255, 140, 0)",
                          boxShadow: "0 0 0 1px rgb(255, 140, 0)",
                        }}
                      />
                    </Box>
                  </Grid>
                </>
              ) : (
                /* 不支持单色调色板的模式 - 隐藏调色板 */
                <Box
                  p={6}
                  borderRadius="lg"
                  bg="rgba(255, 255, 255, 0.1)"
                  border="1px solid rgba(255, 140, 0, 0.2)"
                  textAlign="center"
                  minH="400px"
                  display="flex"
                  flexDirection="column"
                  alignItems="center"
                  justifyContent="center"
                >
                  <Text fontSize="sm" color="black" textAlign="center">
                    {t("1028")}
                  </Text>
                </Box>
              )}
            </Box>
          )}
        </Grid>
      </Box>

      {/* 音频频谱矩阵组件 */}
      {isElectron && showAudioMatrix && (
        <Box
          className="p-6 absolute bottom-[10%] bg-white/20 backdrop-blur-md"
          style={{
            width: `calc(100% - ${lightEffectWidth + 60}px`,
            height: `${lightEffectHeight}px`,
            left: `${lightEffectWidth}px`,
          }}
          borderRadius="lg"
          // bg="black"
          border="1px solid rgba(255, 140, 0, 0.3)"
        >
          <Flex justifyContent="space-between" alignItems="center" mb={4}>
            <Heading size="md" color="black">
              音频频谱矩阵
            </Heading>
            <Flex gap={3} alignItems="center">
              <button
                onClick={handleCloseAudioMatrix}
                style={{
                  padding: "8px 16px",
                  backgroundColor: "#ef4444",
                  color: "white",
                  border: "none",
                  borderRadius: "4px",
                  cursor: "pointer",
                  fontWeight: "bold",
                }}
              >
                关闭
              </button>
            </Flex>
          </Flex>
          <MatrixRenderer
            onMatrixData={async (matrix) => {
              // console.log("🎵 收到音频数据:", matrix);

              // 同步页面预览用的 UI 因子与列级别
              try {
                const raw = Math.max(
                  0,
                  Math.min(1, (matrix as any)?.stats?.avg ?? 0)
                );
                const enhanced = Math.pow(raw, 0.5);
                setUiLightFactor((prev) =>
                  Math.max(0, Math.min(1, prev * 0.6 + enhanced * 0.4))
                );
                if (Array.isArray(matrix?.colLevels)) {
                  setUiColLevels(matrix.colLevels.slice(0, 22));
                }
              } catch (_) {}
            }}
          />
        </Box>
      )}
    </Box>
  );
}

export default KBLightSetting;
